package com.ruoyi.elasticsearch.emq;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.elasticsearch.es.domain.DeviceInfoDTO;
import com.ruoyi.elasticsearch.service.AlarmService;
import com.ruoyi.elasticsearch.service.IDeviceService;
import com.ruoyi.elasticsearch.service.QuotaService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 消息回调类
 */
@Component
@Slf4j
public class EmqMsgProcess implements MqttCallback {

    @Autowired
    private EmqClient emqClient;
    @Autowired
    private AlarmService alarmService;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private IDeviceService deviceService;

    @Override
    public void connectionLost(Throwable throwable) {
    }

//    @Override
//    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
//        String payload = new String(mqttMessage.getPayload());
//        System.out.println("接收到数据："+payload);
//    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        try{
            String payload = new String(mqttMessage.getPayload());
            System.out.println("进来了");
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> payloadMap = mapper.readValue(payload, Map.class);
            System.out.println("接收到数据："+payloadMap);
            //解析数据
            DeviceInfoDTO deviceInfoDTO = quotaService.analysis(topic, payloadMap);
            if(deviceInfoDTO!=null){
                //告警判断
                deviceInfoDTO= alarmService.verifyDeviceInfo(deviceInfoDTO);  //返回包含了告警判断的对象
                //保存设备信息
                deviceService.saveDeviceInfo(deviceInfoDTO.getDevice());
                //保存指标数据
                quotaService.saveQuotaToInflux(deviceInfoDTO.getQuotaList());
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
